package com.steven.ourcontest.contest.view

import android.os.Bundle
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.steven.ourcontest.R
import com.steven.ourcontest.app.AppRouter
import com.steven.ourcontest.base.BaseActivity
import com.steven.ourcontest.contest.viewmodel.SearchMatchViewModel
import com.steven.ourcontest.team.adapter.MatchAdapter
import com.steven.ourcontest.utils.changed
import kotlinx.android.synthetic.main.activity_search_match.*

class SearchMatchActivity : BaseActivity() {
    private val searchMatchViewModel: SearchMatchViewModel by viewModels()
    private val adapter by lazy {
        MatchAdapter(this) { id, _ ->
            AppRouter.openMatchDetailActivity(this, id)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun getViewId(): Int? {
        return R.layout.activity_search_match
    }

    override fun initView() {
        rv_match_list?.adapter = adapter
        et_content?.changed {
            if (!it.isNullOrEmpty()) {
                searchMatchViewModel.editChange(it.toString())
                adapter.listData.clear()
            }
        }
        searchMatchViewModel.matchResponse.observe(this, Observer {
            adapter.listData.addAll(it.data)
            adapter.notifyDataSetChanged()
            smart_refresh?.isVisible = adapter.listData.isNotEmpty()
        })
        smart_refresh.setEnableAutoLoadMore(true)
        smart_refresh.setEnableRefresh(false)
        smart_refresh.setRefreshFooter(ClassicsFooter(this))
        smart_refresh?.setOnLoadMoreListener {
            searchMatchViewModel.queryMatchMore(et_content?.text.toString()) {
                smart_refresh?.finishLoadMore()
            }
        }
    }
}